package cn.sofwin.blog.service.impl;

import cn.sofwin.blog.dao.ArticleDao;
import cn.sofwin.blog.entity.Article;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.ArticleService;
import cn.sofwin.blog.utils.DbUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

/**
 * 服务层
 * @author LetCode
 * @since 1.0
 *
 */
public class ArticleServiceImpl implements ArticleService {
    private ArticleDao articleDao=getSession().getMapper(ArticleDao.class);;
    /** 私有的实例对象，用户实现单例模式 */
    private static ArticleServiceImpl articleService = new ArticleServiceImpl();

    /**
     * 将构造方法设为私有，用于实现单例模式
     */
    private ArticleServiceImpl(){
        super();
    }

    /**
     * 对外提供的静态方法，用于获取服务实例
     * @return
     */
    public static ArticleService getInstance(){
        return articleService;
    }

    @Override
    public SqlSession getSession() {
        return DbUtils.openSession();
    }

    @Override
    public List<Article> all() {

        List<Article> articles=articleDao.selectAll();
        return articles;
    }

    @Override
    public Article getArticleById(int id) {

        return articleDao.selectOne(id);
    }

    @Override
    public void writeArticle(User user, String title, String summary, String content) {
        Article article=new Article();
        article.setUser(user);
        article.setTitle(title);
        article.setSummary(summary);
        article.setContent(content);
        article.setAddTime(new Date());
        article.setStatus(1);
        article.setReadTotal(0);
        article.setCommentTotal(0);
        articleDao.insert(article);
    }

    @Override
    public void edit(String id, String summary, String content) {
        Article article = articleDao.selectOne(Integer.parseInt(id));
        article.setSummary(summary);
        article.setContent(content);
        articleDao.update(article);
    }

    @Override
    public void deleteArticle(int id) {
        articleDao.deleteById(id);
    }
}